#python 火车票信息的查询
import requests
import time
import os
import stat
import string

file_name = 'train_massage.txt'
requests_file = 'request_file.txt'
url1="https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9171"
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko',
          'Cookie':'_uab_collina=161648277360544745517535; JSESSIONID=30218AE01024283F5A1B1706B18FA9EC; _jc_save_fromStation=%u5317%u4EAC%2CBJP; _jc_save_toDate=2021-03-23; _jc_save_wfdc_flag=dc; RAIL_EXPIRATION=1616818599468; RAIL_DEVICEID=cs0v3cw53QMbbn61iQ4_Mg9k3FTpWhUUVqZSveonL7rjFuYLHkYeTU469EFuGU2Ib1lodaSC2nULtX2xXJUFqS07DNzoWAkaZ1qoE8i5TR2oOIhqDUilw4fxDYHxRV3mPssxkBTr03sLuCz82Rx-nof7MSU5x_0C; _jc_save_fromDate=2021-03-23; route=9036359bb8a8a461c164a04f8f50b252; BIGipServerotn=2045247754.64545.0000; BIGipServerpassport=870842634.50215.0000; _jc_save_toStation=%u4E0A%u6D77%2CSHH'
}
txt=requests.get(url1).text

inf=txt[:-2].split("@")[1:] #从数据库取得全国的站点信息
#print(inf)
stations={}
for record in inf:
    rlist=record.split("|")
    #print(rlist)
    stations[rlist[2]]={"cn":rlist[1],"qp":rlist[3],"jp":rlist[4],"num":rlist[5]}  #把车站编码当作key
#print(stations.items()) #Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。

while (1):
    if os.path.exists(requests_file):
        os.chmod(requests_file, stat.S_IRWXU)
        with open(requests_file, "r") as file_object:
            content = file_object.read()
            station = content.split(",")
            origin_station = station[0]
            to_station = station[1]
            chufatime = station[2]
    else:
        continue

    print(origin_station)
    print(to_station)
    print(chufatime)

    for origin_station_list in stations.items():
        if (origin_station == origin_station_list[1]['cn']):
            fromstation = origin_station_list[0]
            print(fromstation)
    for to_station_list in stations.items():
        if (to_station == to_station_list[1]['cn']):
            tostation = to_station_list[0]
            print(tostation)


    qurl="https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT".format(chufatime,fromstation,tostation)
    print(qurl)
    try:
        ainf1=requests.get(url=qurl, headers=header, timeout = (3,7))  #json文件存储当前从出发站到目的站的所有车次的详细信息
    except:
        time.sleep(60)
        ainf1=requests.get(url=qurl, headers=header, timeout = (3,7))  #json文件存储当前从出发站到目的站的所有车次的详细信息
    print(ainf1.json)
    if (ainf1.headers['Content-Type'] == "text/html") :
        print("text/html")
        continue
    if (ainf1.headers['Content-Type'] == "text/plain;charset=UTF-8") :
        print("text/plain;charset=UTF-8")
        continue
    if (ainf1.url == "https://www.12306.cn/mormhweb/logFiles/error.html") :
        continue
    if (ainf1.encoding == 'ISO-8859-1') :
        continue
    print(ainf1)
    ainf = ainf1.json()["data"]["result"]
    print("\n")
    print(ainf)
    result=[]
    for i in ainf:
        list=i.split("|")
        checi=list[3]
        chufa=stations[list[6]]["cn"]
        mudi=stations[list[7]]["cn"]
        ftime=list[8]
        dtime=list[9]
        date=list[13]
        if (ftime != "24:00"):
            if (dtime != "24:00"):
                result.append((checi,chufa,mudi,ftime,dtime,date))
    for i in result:
        for n in range(len(i)):
            with open(file_name, 'a') as file_object:
                file_object.write(i[n]+"|")
            print(i[n],end="\t")
        print()
        with open(file_name, 'a') as file_object:
            file_object.write(",")

    with open(file_name, 'a') as file_object:
            file_object.write(".")

    os.remove(requests_file)
